package cn.com.easttech.gofishing;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class BaseActivity extends AppCompatActivity {

    protected String TAG;

    private BaseActiviyBroadcast baseActiviyBroadcast;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getSimpleName();

        //动态注册广播
        baseActiviyBroadcast = new BaseActiviyBroadcast();
        IntentFilter intentFilter = new IntentFilter("cn.com.easttech.BaseActivity");
        registerReceiver(baseActiviyBroadcast, intentFilter);
    }

    //在销毁的方法里面注销广播
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(baseActiviyBroadcast);//注销广播
    }

    //定义一个广播
    public class BaseActiviyBroadcast extends BroadcastReceiver {

        //接收发送过来的广播内容
        public void onReceive(Context arg0, Intent intent) {
            int closeAll = intent.getIntExtra("closeAll", 0);
            if (closeAll == 1) {
                finish();//销毁BaseActivity
            }
        }

    }

    /**
     * 显示Toast信息
     */
    public void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    private long time = 0;
    protected void exit() {
        if (System.currentTimeMillis() - time > 2000) {
            time = System.currentTimeMillis();
            showToast("再点击一次退出应用程序");
        } else {
            exitNow();
        }
    }

    protected void exitNow() {
        Intent intent = new Intent("cn.com.easttech.BaseActivity");
        intent.putExtra("closeAll", 1);
        sendBroadcast(intent);//发送广播
    }
}